package demo2;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 邓大帅
 * Date: 2024-01-12
 * Time: 14:21
 */
public class MyArrayList {
    public int[] elem;
    public int useSize;
    public static final int DEFAULT_SIZE = 10;
    public MyArrayList() {
        elem = new int[DEFAULT_SIZE];
    }
    public void display() {
        for (int i = 0; i < this.useSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }
    public int getUseSize() {
        return this.useSize;
    }
    public boolean contains(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if (this.elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }
    public int indexOf(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if (this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }
    public void add(int data) {
        if (this.isFull()) {
            reSize();
        }
        this.elem[this.useSize] = data;
        this.useSize++;
    }
    public void add(int pos, int data) throws IndexOutOfException {
        checkAddIndex(pos);
        if (this.isFull()) {
            reSize();
        }
        for (int i = useSize - 1; i >= pos; i--) {
            this.elem[i+1] = this.elem[i];
        }
        elem[pos] = data;
        this.useSize++;
    }

    /**
     * 扩容
     */
    private void reSize() {
        this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
    }


    /**
     * 检查pos是否合法
     * @param pos
     * @return
     */
    private void checkAddIndex(int pos) throws IndexOutOfException {
        if (pos < 0 || pos > this.useSize) {
            throw new IndexOutOfException("输入的加入位置不合法，请检查位置的合法性！");
        }
    }
    /**
     * 判断线性表是否满了
     * @return
     */
    public boolean isFull() {
        return this.useSize == this.elem.length;
    }

    public int get(int pos) {
        checkIndex(pos);
        return this.elem[pos];
    }

    private void checkIndex(int pos) throws IndexOutOfException {
        if (pos < 0 || pos >= this.useSize) {
            throw new IndexOutOfException("输入的位置不合法，请检查位置的合法性！");
        }
    }

    public void set(int pos, int data) {
        checkIndex(pos);
        this.elem[pos] = data;
    }
    public boolean remove(int toRemove) {
        int index = indexOf(toRemove);
        if (index == -1) {
            System.out.println("没有这个数据");
            return false;
        }
        for (int i = index; i < this.useSize - 1; i++) {
            this.elem[i] = this.elem[i+1];
        }
        this.useSize--;
        this.elem[useSize] = 0;
        return true;
    }
    public void clear() {
        /*for (int i = 0; i < this.useSize; i++) {
            this.elem[i] = null;
        }*/
        this.useSize = 0;
    }
}
